/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.service.hive;

import com.chinamobile.cmss.lakehouse.common.Constants;
import com.chinamobile.cmss.lakehouse.common.utils.PropertyUtils;

import java.sql.Connection;

import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HivePoolConfig {

    private int maxTotalPerKey = PropertyUtils.getInt(Constants.HIVE_MAX_TOTAL_PER_KEY);
    private int maxIdlePerKey = PropertyUtils.getInt(Constants.HIVE_MAX_IDLE_PER_KEY);
    private int evictorShutdownTimeout = PropertyUtils.getInt(Constants.HIVE_EVICTOR_SHUTDOWN_TIMEOUT);
    private int minEvictableIdleTime = PropertyUtils.getInt(Constants.HIVE_MIN_EVICTABLE_IDLE_TIME);
    private int maxWait = PropertyUtils.getInt(Constants.HIVE_MAX_WAIT);
    private int timeBetweenEvictionRunsMillis = PropertyUtils.getInt(Constants.HIVE_TIME_BETWEEN_EVICTION_RUNS);

    @Bean
    public HiveConnectionPool hiveConnectionPool(HiveConnector hiveConnector) {
        GenericKeyedObjectPool<String, Connection> genericKeyedObjectPool =
            new GenericKeyedObjectPool<>(new HiveConnectionFactory(hiveConnector),
                poolConfig());
        return new HiveConnectionPool(genericKeyedObjectPool);
    }

    private GenericKeyedObjectPoolConfig poolConfig() {
        GenericKeyedObjectPoolConfig conf = new GenericKeyedObjectPoolConfig();
        conf.setMaxTotalPerKey(maxTotalPerKey);
        conf.setMaxIdlePerKey(maxIdlePerKey);
        conf.setBlockWhenExhausted(true);
        conf.setEvictorShutdownTimeoutMillis(evictorShutdownTimeout);
        conf.setMinEvictableIdleTimeMillis(minEvictableIdleTime);
        conf.setMaxWaitMillis(maxWait);
        conf.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        return conf;
    }
}
